package com.epfresh.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.epfresh.R;
import com.epfresh.adapter.CityAddressSelectedAdapter;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.City;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.bean.CityAddress;
import com.epfresh.bean.CityAddressBox;
import com.epfresh.global.BaseActivity;
import com.epfresh.location.LocationService;
import com.epfresh.utils.FileCache;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CityAddressSelectedActivity extends BaseActivity {


    private LocationService locationService;

    private ListView lv;

    private boolean isFirst;

    private CityAddress cityAddress;

    //记录当前位置
    private CityAddressBox locationBox = new CityAddressBox();

    private CityAddressSelectedAdapter adapter;

    private List<CityAddressBox> list = new ArrayList<>();

    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            Log.e("city", "onReceive");
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                String city = location.getCity();
                String province = location.getProvince();
                String cityCode = location.getCityCode();
                Log.e("city", "province:" + province + "");
                Log.e("city", "city:" + city + "");
                Log.e("city", "citycode:" + cityCode + "");
                if (locationBox.getCityName() != null && locationBox.getCityName().equals(city) && locationBox.getCityId() != null && !"".equals(locationBox.getCityId())) {
                } else {
                    locationBox.setCityName(city);
                    locationBox.setCityId(getLocationCityId(city, province));
                    locationBox.setLocation(city);
                    adapter.notifyDataSetChanged();
                }
            } else {//定位失败
                locationBox.setLocation("定位失败");
                locationBox.setCityName(null);
                locationBox.setCityId(null);
                adapter.notifyDataSetChanged();
            }

        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_address_selected);

        if (savedInstanceState != null) {
            getIntent().putExtra("isFirst", savedInstanceState.getBoolean("isFirst"));
        }

        isFirst = getIntent().getBooleanExtra("isFirst", false);
        initView();
        initLocation();
        requestCity();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isFirst", isFirst);
        super.onSaveInstanceState(outState);
    }

    private void initView() {
        baseback.setVisibility(View.VISIBLE);

        if (isFirst) {
            toolbarTitle.setText("选择区域");
        } else {
            City city = ApplicationHelper.getInstance().getCity();
            String cityName = city.getCityName();
            if (cityName != null && !"".equals(cityName)) {
                toolbarTitle.setText("选择区域-" + cityName);
            }
        }
        toolbarTitle.setVisibility(View.VISIBLE);
        lv = (ListView) findViewById(R.id.lv);

        adapter = new CityAddressSelectedAdapter(this, list);

        adapter.setOnCitySelectListener(new CityAddressSelectedAdapter.OnCitySelectListener() {
            @Override
            public void onCitySelect(int position, int childPosition, String cityName, String cityId, String lng, String lat, String addressId, boolean isLocation) {

                Intent intent = new Intent(CityAddressSelectedActivity.this, HomeActivity.class);
                if (isFirst) {
                    City city = ApplicationHelper.getInstance().getCity();
                    if (cityId != null && !"".equals(cityId)) {
                        city.setCityId(cityId);
                        city.setCityName(cityName);
                        ApplicationHelper.getInstance().updateCity(city);
                    }
                } else {
                    ApplicationHelper.getInstance().getCity().setAddressIdCache(addressId);
                    intent.putExtra("cityId", cityId);
                    intent.putExtra("cityName", cityName);
                    intent.putExtra("lng", lng);
                    intent.putExtra("lat", lat);
                    intent.putExtra("home_tab_index",0);
                }
                if (addressId != null && !"".equals(addressId)) {//选择收货地址
                    requestDefAddress(addressId, intent);
                    MobclickAgent.onEvent(CityAddressSelectedActivity.this, "Click_Locate_CellAddress");
                } else {
                    startActivity(intent);
                    finish();
                }
            }
        });


        lv.setAdapter(adapter);

    }

    private void initLocation() {

        locationService = new LocationService(getApplicationContext());

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                ) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    0x1991);
        } else if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                ) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    0x1993);
        } else {
            locationService.start();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0x1993:
            case 0x1991: {
                // If requestSilent is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    locationService.start();
                } else {
//                    toast("位置权限获取失败");
                    locationBox.setLocation("定位失败");
                    locationBox.setCityName(null);
                    locationBox.setCityId(null);
                    adapter.notifyDataSetChanged();
                }
                return;
            }

        }
    }

    @Override
    public void onStop() {
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
        locationService.registerListener(mListener);
        //注册监听
        int type = getIntent().getIntExtra("from", 0);
        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            locationService.setLocationOption(locationService.getOption());
        }
    }


    public void onClick(View view) {
        switch (view.getId()) {
            // 返回上一页
            case R.id.now_city:

                break;
            case R.id.baseback:
                Intent intent = new Intent(CityAddressSelectedActivity.this, HomeActivity.class);
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }
    }

    private String getLocationCityId(String cityName, String province) {

        if (locationBox != null && cityAddress != null &&
                ((cityName != null && !"".equals(cityName)) ||
                        (province != null && !"".equals(province)))) {
            return cityAddress.getCityId(cityName, province);
        }
        return null;
    }

    @Override
    public void onException(int tag) {
        requestCity();
    }

    OnRequestListener<CityAddress> onRequestCityListener = new OnRequestListener<CityAddress>() {
        @Override
        public CityAddress jsonToObj(String s) {
            saveOpenAddress(s);
            return new Gson().fromJson(s, CityAddress.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            showExceptionView(R.mipmap.icon_error, "网络请求失败", 1);
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

            showExceptionView(R.mipmap.icon_error, o + "", 1);
        }

        @Override
        public void onStart(Object o) {

            showProgressView();
        }

        @Override
        public void onResponse(ResponseEntity<CityAddress> responseEntity, Object o) {
            CityAddress responseElement = responseEntity.getResponseElement();

            showMainView();
            cityAddress = responseElement;
            if (responseElement != null) {
                City city = ApplicationHelper.getInstance().getCity();
                String addressId = city.getAddressId();
                String cityId = city.getCityId();
                if (getUser() != null && getUser().getAccess_token() != null && !"".equals(getUser().getAccess_token())) {
                    if (isFirst) {
                        responseElement.getCityBoxMaker(list, locationBox, true, null, null);
                    } else {
                        responseElement.getCityBoxMaker(list, locationBox, true, addressId, cityId);
                    }
                } else {
                    if (isFirst) {
                        responseElement.getCityBoxMaker(list, locationBox, false, null, null);
                    } else {
                        responseElement.getCityBoxMaker(list, locationBox, false, addressId, cityId);
                    }
                }
                locationBox.setCityId(getLocationCityId(locationBox.getCityName(), locationBox.getProvince()));
                adapter.notifyDataSetChanged();
            }
        }
    };

    public void requestCity() {
        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_account_app_deliveryAddress);
        Map<String, String> map = new HashMap<>();
        map.put("version", "0");
        data.setParameters(map);
        request(data, AppPurchaseRouterConstant.cmd_account_app_deliveryAddress, onRequestCityListener);
    }

    OnRequestListener<Map<String, String>> onAddressRequestListener = new OnRequestListener<Map<String, String>>() {
        @Override
        public Map<String, String> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, String>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

            hideProgressDialog();
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

            hideProgressDialog();
        }

        @Override
        public void onStart(Object o) {

            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<Map<String, String>> responseEntity, Object o) {

            hideProgressDialog();
            if (o != null && o instanceof RequestTag) {
                RequestTag tag = (RequestTag) o;
                o = tag.tag;
                if (o != null) {
                    Intent intent = (Intent) o;
                    startActivity(intent);
                    finish();
                }
            }

        }
    };

    public void requestDefAddress(String addressId, Intent intent) {
        RequestEntityMap data = new RequestEntityMap();
        data.setCmd(AppPurchaseRouterConstant.cmd_account_address_setDefault);
        data.putParameter("id", addressId);
        data.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        data.putParameter("isDefault", true);
        RequestTag tag = new RequestTag();
        tag.tag = intent;
        request(data, tag, onAddressRequestListener);
    }


    public void saveOpenAddress(String a) {
        FileCache fileCache = new FileCache(mContext);
        fileCache.saveFile((fileCache.getCachePath() + "epfresh_open_area_data.txt"), a.toString());
        Log.i("file", fileCache.getCachePath() + "epfresh_open_area_data.txt");
    }

}
